package thirdFragment.fragment;


import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.example.xuegengwang.xuegengwang.R;
import com.google.gson.Gson;

import common.Constant;
import https.InterNetController;
import https.handler.ErrorPageHandler;
import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;
import utils.MyLogUtils;
import view.MyPtrRefresh_LoadView;
import view.NetworkImageHolderView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import common.BaseFragment;
import thirdFragment.adapter.CollegeLvAdapter;
import thirdFragment.bean.CollegeBean;

/**
 * 高校新闻列表
 */
@SuppressLint("ValidFragment")
public class College extends BaseFragment implements OnItemClickListener {
    private ConvenientBanner convenientBanner;//轮播图
    private View view;
    private View headerView;
    private ListView listView;
    private CollegeLvAdapter collegeLvAdapter;
    private ArrayList<CollegeBean.BannerBean> bannerBeenList;//banner图的数组
    private ArrayList<CollegeBean.NewsListBean> newsListBeenList = new ArrayList<>();//新闻的数组
    private MyPtrRefresh_LoadView college_refresh_layout;///上拉加载下拉刷新
    private List<String> networkImages;
    private int page = 1;//后台给的当前数据页
    private int topNewsNum = 0;//置顶文章所在数组的最后的位置
    private final int INIT = 0;//第一次加载
    private final int ONREFRESH = 1;//刷新
    private final int ONLOAD = 2;//加载

    private boolean firstLoad = true;
    private static final String TAG = "College";

    private ErrorPageHandler myHandler = new ErrorPageHandler(true) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constant.ERROR_CODE_SUCCESS:
                    MyLogUtils.e(TAG, msg.arg1 + "");
                    Gson gson = new Gson();
                    CollegeBean collegeBean = gson.fromJson((String) msg.obj, CollegeBean.class);
                    List<CollegeBean.BannerBean> banner = collegeBean.getBanner();//添加banner图
                    if (banner != null) {
                        bannerBeenList = (ArrayList<CollegeBean.BannerBean>) banner;
                        setBanner(bannerBeenList);
                    }
                    ArrayList<CollegeBean.NewsListBean> arrayList = (ArrayList<CollegeBean.NewsListBean>) collegeBean.getNewsList();
                    switch (msg.arg1) {
                        case INIT:
                            //第一页拿的是有置顶的
                            if (arrayList != null) {
                                firstLoad = false;//第一次请求成功
                                newsListBeenList.clear();
                                for (int i = 0; i < arrayList.size(); i++) {
                                    if ("1".equals(arrayList.get(i).getIstop())) {
                                        // 文章置顶
                                        topNewsNum++;
                                        newsListBeenList.add(0, arrayList.get(i));
                                    } else {
                                        newsListBeenList.add(arrayList.get(i));
                                    }
                                }
                            }
                            break;
                        case ONREFRESH:
                            if (arrayList != null) {
                                for (int i = 0; i < arrayList.size(); i++) {
                                    newsListBeenList.add(topNewsNum, arrayList.get(i));
                                }
                            }
                            break;
                        case ONLOAD:
                            if (arrayList != null) {
                                for (int i = 0; i < arrayList.size(); i++) {
                                    newsListBeenList.add(arrayList.get(i));
                                }
                            }
                            break;
                        default:
                            break;
                    }
                    collegeLvAdapter.notifyDataSetChanged();
                    break;
                case Constant.ERROR_CODE_FINISH:
                    college_refresh_layout.OnRefreshComplete();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (this.getMyActivity() != null) {
            if (view == null) {
                view = LayoutInflater.from(getMyActivity()).inflate(R.layout.fragment_college, null);
            }
            initView();
            initListView();
            getDateFromInterNet(page, INIT, true);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return view;
    }

    private void initView() {
        headerView = LayoutInflater.from(getMyActivity()).inflate(R.layout.college_header, null);
        college_refresh_layout = (MyPtrRefresh_LoadView) view.findViewById(R.id.college_refresh_layout);
        college_refresh_layout.setPtrHandler(new PtrDefaultHandler2() {
            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                page += 1;
                getDateFromInterNet(page, ONLOAD, false);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                if (firstLoad) {
                    getDateFromInterNet(page = 1, INIT, false);
                } else {
                    getDateFromInterNet(++page, ONREFRESH, false);
                }
            }
        });
        listView = (ListView) view.findViewById(R.id.college_lv);
        convenientBanner = (ConvenientBanner) headerView.findViewById(R.id.college_banner);
    }

    private void initListView() {
        listView.addHeaderView(headerView);
        collegeLvAdapter = new CollegeLvAdapter(getMyActivity(), newsListBeenList);
        listView.setAdapter(collegeLvAdapter);
    }

    private void setBanner(ArrayList<CollegeBean.BannerBean> bannerBeenList) {
        networkImages = new ArrayList<>();
        for (int i = 0; i < bannerBeenList.size(); i++) {
            networkImages.add(bannerBeenList.get(i).getImage());
        }
        //设置轮播图片
        convenientBanner.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {
            @Override
            public NetworkImageHolderView createHolder() {
                return new NetworkImageHolderView();
            }
        }, networkImages)
                .setPointViewVisible(true)    //设置指示器是否可见
                .startTurning(2000)
                .setPageIndicator(new int[]{R.mipmap.main_doc1, R.mipmap.main_doc})
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.ALIGN_PARENT_RIGHT)
                .setOnItemClickListener(this);   //设置指示器圆点;
    }

    @Override
    public void onItemClick(int position) {
        //banner图点击效果
        getMyActivity().drumpActivity(bannerBeenList.get(position).getLink());
    }

    private void getDateFromInterNet(int page, int type, boolean waitingDialog) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("page", String.valueOf(page));
        hashMap.put("type", "college");
        new InterNetController(getMyActivity(), Constant.NEWLIST, myHandler, hashMap, type, waitingDialog);
    }
}